from rest_framework import filters
from rest_framework.metadata import BaseMetadata
from rest_framework.pagination import PageNumberPagination


class DynamicFieldsSerializerMixin(object):
    ''' 
    可以动态地改变序列化的输出字段 （也叫指定字段输出，如下输出{'id': xxx, 'name': xxx}）
    例如：xxxSerializer(myModel, fields={'id', 'name'})
    '''
    def __init__(self, *args, **kwargs):
        # Don't pass the 'fields' arg up to the superclass
        fields = kwargs.pop('fields', None)

        # Instantiate the superclass normally
        super().__init__(*args, **kwargs)

        if fields is not None:
            # Drop any fields that are not specified in the `fields` argument.
            allowed = set(fields)
            existing = set(self.fields)
            for field_name in existing - allowed:
                self.fields.pop(field_name)


class DynamicFieldsViewMixin(object):
    def get_serializer(self, *args, **kwargs):

        serializer_class = self.get_serializer_class()

        fields = None
        if self.request and self.request.method == 'GET':
            query_fields = self.request.query_params.get("fields", None)

            if query_fields:
                fields = tuple(query_fields.split('.'))

        kwargs['context'] = self.get_serializer_context()
        kwargs['fields'] = fields
        return serializer_class(*args, **kwargs)


class IsOwnerFilterBackend(filters.BaseFilterBackend):
    """
    自定义过滤器
    然后将'IsOwnerFilterBackend'全路径放到REST_FRAMEWORK中filter的位置
    """
    def filter_queryset(self, request, queryset, view):
        # 实现自定义过滤逻辑
        return queryset.filter(owner=request.user)


class MinimalMetadata(BaseMetadata):
    """
    Don't include field and other information for `OPTIONS` requests.
    Just return the name and description.
    """
    def determine_metadata(self, request, view):
        return {
            'name': view.get_view_name(),
            'description': view.get_view_description()
        }


class StandardPagination(PageNumberPagination):
    page_size_query_param = 'page_size'
    max_page_size = 500